#include "add.h"

int search_id(const char * filename , int id)
{
	int fd = open(filename,O_RDONLY);
	if(fd == -1)
	{
		perror("open");
		exit(-1);
	}
	
	employee emp;
	
	while(read(fd,&emp,sizeof(emp)))
	{
		if(emp.id == id)
			return 1;
	}
	return 0;	
	close(fd);
}

void write_file(const char * filename)
{	
	int fd = open(filename,O_CREAT | O_RDWR | O_TRUNC , 0666);
	if(fd == -1)
	{
		perror("open");
		exit(-1);
	}
	
	char name[30];
	employee emp;
	char flag = 'Y';
	
	while(1)
	{
		printf("please input the id : ");
		scanf("%d",&emp.id);
		scanf( "%*[^\n]");
	    scanf("%*c");
	    
	    if(!search_id(filename,emp.id))
	    {
	    	printf("please input the emp's name : ");
			fgets(name,sizeof(name),stdin);
			if(strlen(name) == sizeof(name) - 1 && name[sizeof(name) - 2] != '\n')
			{
				scanf( "%*[^\n]");
		        scanf( "%*c");
			}
			strcpy(emp.name , name);
			
			printf("please input the emp's sal : ");
			scanf("%lf",&emp.sal);
			scanf( "%*[^\n]");
		    scanf("%*c");
		    
		    write(fd,&emp,sizeof(emp));
		    
		    printf("Do you continue to import , Y or N ? ");
		    scanf("%c",&flag);
			if((flag == 'N') || (flag == 'n'))
				break;
		}
		else
		{
			printf("Sorry , the id you input exists , please try again .");
		}				
	}	
	close(fd);
}

void read_file(const char * filename)
{
	int fd = open(filename,O_RDONLY);
	if(fd == -1)
	{
		perror("open");
		exit(-1);
	}
	employee emp;	
	while(read(fd,&emp,sizeof(emp)))
	{
		printf("Employee's id : %d \n",emp.id);
		printf("Employee's name : %s \n",emp.name);
		printf("Employee's sal : %lf \n",emp.sal);
	}
	close(fd);
}
